/** 存放一些常用的方法... */
import store from "@/store/index.js";
import JSEncrypt from "@/static/jsencrypt.js";
import permision from "@/js_sdk/wa-permission/permission.js"

/**
 * 获取对字符串进行加密后的数据
 * @param {string} str 需要加密的字符串
 * @param {string} key 加密的key
 * @return {string}
 * */
export const getEncryptAfterStr = (str = "", key = "") => {
    // 判断是否存在
    if(!str) {
        return "";
    }
    // 获取加密的对象
    const encrypt = new JSEncrypt();
    // 设置key
    encrypt.setPublicKey('-----BEGIN PUBLIC KEY-----' + key + '-----END PUBLIC KEY-----');
    // 返回加密后的数据
    return encrypt.encrypt(str);
}


/** 获取系统的高度信息 */
export const getSystemHeightInfo = () => {
	// 获取系统信息...
	const {
		statusBarHeight,
		safeAreaInsets: {
			bottom
		}
	} = uni.getSystemInfoSync();

	return {
		// 顶部状态栏高度
		stateHeight: statusBarHeight,
		// 一些特殊手机底部的高度
		bottomHeight: bottom,
		// 目前 narbar 高度 (px)
		navbarHeight: 47,
		// 目前 tabbar 高度 (px)
		tabbarHeight: 50
	}
}

/**
 * 将图片转为base64
 * @param {string} url 图片路径
 */
export const getBase64ByImage = url => {
	return new Promise(resolve => {
		uni.getFileSystemManager().readFile({
			filePath: url,
			encoding: 'base64',
			success: res => {
				resolve('data:image/jpeg;base64,' + res.data);
			}
		});
	});
}

function urlToBlob(dataurl, fileType) {
	dataurl = dataurl.replace('-', '+').replace('_', '/').split(';base64,')[1] //以防生成的url字符串不规范
	// var raw = decodeURIComponent(escape(window.atob(dataurl))) // 用decodeURIComponent防止base64编码错误
	var raw = window.atob(dataurl) // 用decodeURIComponent防止base64编码错误
	var rawlength = raw.length
	var uint8array = new Uint8Array(rawlength)
	for (var i = 0; i < rawlength; i++) {
		uint8array[i] = raw.charCodeAt(i)
	}
	var blob = new Blob([uint8array], {
		type: 'image/' + fileType
	})
	console.log(blob)
	return blob
}
// base转Blob
function base64ToBlob(base64) {
	var arr = base64.split(','),
		mime = arr[0].match(/:(.*?);/)[1],
		bstr = atob(arr[1]),
		n = bstr.length,
		u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new Blob([u8arr], {
		type: mime
	});
}
export const imgFun = (file) => {
	return new Promise(async resolve => {
		// 对图片进行压缩
		let path = file.thumb ? file.thumb : file;
		// 图片格式类型
		const imageTypeArray = ["png", "jpg", "jpeg", "bmp"];

		// 判断文件类型
		if (file.thumb) {
			const fileType = file.thumb.substring(file.thumb.lastIndexOf(".") + 1, file.thumb.length);
			console.log(fileType,'==');
			// if(imageTypeArray.includes(fileType)) {
			const url = await getCompressionImage(file.thumb, {
				size: file.size,
				fileType
			});
			if (url) {
				path = url;
			}
			// }
		}
		console.log(path,'113conmmonjs')
		resolve(path);
	});
}
/**
 * 处理对图片进行压缩
 * 配合compression-image组件一起使用，在需要用到的页面引入compression-image组件就能对图片进行压缩
 * 专属方法，勿用！
 * @param {string} url 图片路径
 * @param {number} size 文件大小
 * */
export const getCompressionImage = (url, {
	size = 0,
	fileType = 'image/jpeg'
}) => {
	return new Promise(async resolve => {
		// 获取this对象
		const _this = store.getters.getCompressionImageThis;
		// 判断this是否存在
		if (!_this) {
			resolve(url);
		}
		// 默认判断的size
		const defaultSize = 1024 * 1024;
		// 画布的尺寸
		const canvasWidth = 1000;
		const canvasHeight = 1000;
		// 获取屏幕高度
		const {
			windowWidth,
			windowHeight
		} = uni.getSystemInfoSync();
		// 获取canvas上下文对象
		const context = wx.createCanvasContext("compression-image", _this);
		// 清空画布 - 这边的 清空尺寸 来自于compression-image组件画布的大小
		context.clearRect(0, 0, canvasWidth, canvasHeight);

		// 图片缩放的比例
		let ratio = 1;
		// 判断是否需要缩放
		if (size > defaultSize) {
			ratio = Math.sqrt(size / defaultSize);
		}

		// 获取图片的信息
		uni.getImageInfo({
			src: url,
			success: res => {
				let {
					path,
					width,
					height
				} = res;

				width = width / ratio;
				height = height / ratio;

				// 判断缩放后的是否超出画布
				if (width > canvasWidth || height > canvasHeight) {
					if (width > height) {
						ratio = width / canvasWidth;
					} else {
						ratio = height / canvasHeight;
					}
					width = width / ratio;
					height = height / ratio;
				}
				// 将图片绘制到canvas中
				context.drawImage(path, 0, 0, width, height);
				console.log(context,_this, '----888-=-');
				// 进行绘制...
				context.draw(false, () => {
					console.log(22);
					// 保存图片为临时路径
					setTimeout(() => {
						wx.canvasToTempFilePath({
							canvasId: "compression-image",
							x: 0,
							y: 0,
							width: width,
							height: height,
							destWidth: width,
							destHeight: height,
							fileType: 'jpg',
							success: res => {
								console.log(res);
								resolve(res.tempFilePath);
							},
							fail: err => {
								console.log(err,'err')
								resolve(url);
							}
						}, _this);
					},1000)
				});
			},
			fail: (e) => {
				console.log(e,'e')
				resolve(url);
			},
		});
	});
}

/**
 * 判断是否是正整数
 * @param {string|number} num 需要判断的值
 * @return {boolean}
 */
export const isPositiveInteger = num => {
 return /^[0-9]*$/.test(num.toString());
}

/**
 * @param {Object} permissionID 判断是否获取到对应的权限
 */
export async function getPermission(permissionID){
	var result = await permision.requestAndroidPermission(permissionID)
	var strStatus
	if (result == 1) {
		strStatus = "已获得授权"
	} else if (result == 0) {
		strStatus = "未获得授权"
	} else {
		strStatus = "被永久拒绝权限"
	}
	// uni.showModal({
	//     content: permisionID + strStatus,
	//     showCancel: false
	// });
	console.log(strStatus, '是否获取到了权限');
	return strStatus
}
 
/* 获取表单校验的结果
 * @param {any} form 校验的表单
 * @param {Array} excludeArray 不校验的表单中的key
 * */
export const getFormCheckResult = (form, excludeArray = []) => {
    for (const key in form) {
        if (!excludeArray.includes(key)) {
            if(typeof form[key] === 'boolean') {
                continue;
            }
            else if (typeof form[key] === 'string') {
                if (!form[key].trimStart().trimEnd()) {
                    return false;
                }
            }
            else if (!form[key]) {
                return false;
            }
            else if (typeof form[key] === 'object') {
                if (JSON.stringify(form[key]) === "{}" || JSON.stringify(form[key]) === "[]") {
                   return false;
                }
            }
        }
    }
    return true;
}

/**
 * 对数字处理，保留小数
 * @param num {number} 需要处理的数字
 * @param max {number} 判断最大值
 * @param replace {number} 替换的值
 * @param digit {number} 保留几位
 * */
export const reserveDecimalPoint = (num, max, replace, digit = 2) => {
    let str
    let digitStr = ''
    for (let i = 0; i < digit; i++) {
        digitStr += '0'
    }
    if (Number(num) >= Number(max)) {
        str = replace
    } else {
        str = (parseInt(parseInt(num * Number(`1${digitStr}`) * 10) / 10) / Number(`1${digitStr}`)).toString()
        const index = str.indexOf('.')
        if (index !== -1 && str.length - 1 - index < digit) {
            str = str.slice(0, index) + '.' + str.slice(index + 1, str.length).padEnd(digit, '0')
        } else if (index === -1 && digit > 0) {
			str += `.${'0'.padEnd(digit, '0')}`
		}
    }
    return str
}